package com.berry.MedCheck;

import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.*;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.*;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created with IntelliJ IDEA.
 * User: Airay.Rong
 * Date: 13-12-4
 * Time: 下午7:24
 * To change this template use File | Settings | File Templates.
 */
public class ChooseBtActivity extends Activity implements AdapterView.OnItemClickListener, View.OnClickListener {
	private SimpleAdapter mListAdapter;
	private ArrayList mArray;
	private ListView mBTList;
	private Button mBtnClose;
	private Button mBtnRestart;
	private Button mBtnBind;
	private BluetoothAdapter mBtAdapter   ;
	private boolean bBounded = false;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.choose_bt_activity);
		mBTList = (ListView) findViewById(R.id.bt_list);
		mBTList.setDivider(null);

		mArray = new ArrayList<HashMap<String, Object>>();
		mListAdapter = new SimpleAdapter(this,
				mArray,
				R.layout.bt_item,
				new String[]{"name", "mac", "bound"},
				new int[]{R.id.name, R.id.mac, R.id.bound});
		mBTList.setAdapter(mListAdapter);
		mBTList.setOnItemClickListener(this);

		mBtnClose = (Button) findViewById(R.id.btn_close);
		mBtnClose.setVisibility(View.GONE);
		mBtnClose.setOnClickListener(this);

		mBtnRestart = (Button) findViewById(R.id.btn_restart);
		mBtnRestart.setVisibility(View.GONE);
		mBtnRestart.setOnClickListener(this);

		mBtnBind = (Button) findViewById(R.id.btn_bind);
		mBtnBind.setVisibility(View.GONE);
		mBtnBind.setOnClickListener(this);



	}

	@Override
	protected void onResume() {
		super.onResume();
		startBT();
	}

	private void startBT() {
		IntentFilter filter = new IntentFilter();
		filter.addAction(BluetoothDevice.ACTION_FOUND);
		filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
		filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
		filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
		registerReceiver(mBTReceiver, filter);



		mBtAdapter= BluetoothAdapter.getDefaultAdapter();
		if (mBtAdapter == null) {
			return;
		}
		if (!mBtAdapter.isEnabled()) {
			mBtAdapter.enable();
		}
		mBtAdapter.startDiscovery();
	}

//	private void setBTDiscoverTime() {
//		Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
//		discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, Utils.BT_DISCOVER_TIME);
//		startActivityForResult(discoverableIntent, Utils.INTENT_RESULT_BTDISCOVERTIME);
//	}
	private void callBTSetting() {
		Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
		// 设置蓝牙可见性，最多300秒
		intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, Utils.BT_DISCOVER_TIME);
		startActivityForResult(intent, Utils.INTENT_RESULT_BTSETTING);
	}


	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == Utils.INTENT_RESULT_BTSETTING) {
			if (resultCode == Activity.RESULT_OK) {
				mBtAdapter.startDiscovery();
			} else {
				showBTFailDialog();
			}
		}
		if (requestCode == Utils.INTENT_RESULT_BTDISCOVERTIME) {
			if (resultCode == Utils.BT_DISCOVER_TIME) {
				mBtAdapter.startDiscovery();
			} else {
				showBTDiscoverTimeFailDialog();
			}
		}
	}
	private void showBTDiscoverTimeFailDialog() {
		AlertDialog alert = new AlertDialog.Builder(this).create();
		alert.setCanceledOnTouchOutside(false);
		alert.setMessage(this.getResources().getText(R.string.bt_discover_time_must_set));
		alert.setTitle(R.string.notify);
		//alert.setIcon(android.R.attr.alertDialogIcon);
		alert.setButton(DialogInterface.BUTTON_POSITIVE,this.getResources().getText(R.string.ok), new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				//setBTDiscoverTime();
			}
		});
		alert.setButton(DialogInterface.BUTTON_NEGATIVE,this.getResources().getText(R.string.cancel), new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
			}
		});

		alert.show();
	}
	private void showBTFailDialog() {
		AlertDialog alert = new AlertDialog.Builder(this).create();
		alert.setCanceledOnTouchOutside(false);
		alert.show();


		Window window = alert.getWindow();
		window.setContentView(R.layout.my_alert_dialog);
		TextView tv = (TextView) window.findViewById(R.id.message);
		tv.setText(this.getResources().getText(R.string.bt_must_open));
		Button btnCancel = (Button) window.findViewById(R.id.btn_cancel);
		btnCancel.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				mBtnClose.setVisibility(View.VISIBLE);
			}
		});
		Button btnOK = (Button) window.findViewById(R.id.btn_ok);
		btnOK.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				callBTSetting();
			}
		});
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();    //To change body of overridden methods use File | Settings | File Templates.
		unregisterReceiver(mBTReceiver);
	}

	private void colosBT() {
		mBtAdapter.disable();
	}

	private boolean checkDuplicateBT(HashMap<String, Object> mapNew) {
		for (int i = 0; i < mArray.size(); i++) {
			HashMap<String, Object> map = (HashMap<String, Object>) mArray.get(i);
			if (map.get("mac").equals(mapNew.get("mac"))) {
				return false;
			}
		}
		return true;
	}
	private BroadcastReceiver mBTReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (BluetoothDevice.ACTION_FOUND.equals(action)){
				BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
				HashMap<String, Object> map = new HashMap<String, Object>();
				Log.d(Utils.TAG1, "Get BT device:" + device.getName() + "-" + device.getAddress());
				map.put("name", device.getName());
				map.put("mac", device.getAddress());
				if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
					map.put("bound", getResources().getString(R.string.bind));
					bBounded = true;
				} else {
					map.put("bound", getResources().getString(R.string.space ));
				}
				if (checkDuplicateBT(map) == true) {
					mArray.add(map);
					mListAdapter.notifyDataSetChanged();
				}
			}
			if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
				mBtnRestart.setVisibility(View.VISIBLE);
			}
			if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
				mBtnRestart.setVisibility(View.GONE);
				mArray.clear();
			}
			if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)){
				BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
				if (device == null) {
					return;
				}
				int bondState = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR);
				if (bondState == BluetoothDevice.BOND_NONE) {
					int reason = intent.getIntExtra("android.bluetooth.device.extra.REASON",BluetoothDevice.ERROR);
					showUnbondMessage(context, device.getName(), reason);
				}
			}

		}
		private void showUnbondMessage(Context context, String name, int reason) {
			int errorMsg;

			switch (reason) {
				case 1:
					errorMsg = R.string.bluetooth_pairing_pin_error_message;
					break;
				case 2:
					errorMsg = R.string.bluetooth_pairing_rejected_error_message;
					break;
				case 4:
					errorMsg = R.string.bluetooth_pairing_device_down_error_message;
					break;
				case 5:
				case 6:
				case 7:
				case 8:
					errorMsg = R.string.bluetooth_pairing_error_message;
					break;
				default:
					return;
			}
			String message = context.getString(errorMsg, name);
			Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
		}
	};



	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		mBtAdapter.cancelDiscovery();
		// Get the device MAC address, which is the last 17 chars in the View
		LinearLayout container = (LinearLayout) view;
		TextView tvName = (TextView) container.findViewById(R.id.name);
		TextView tvMac = (TextView) container.findViewById(R.id.mac);
		String address = tvMac.getText().toString();
		String name = tvName.getText().toString();
		Intent intent = new Intent();
		intent.putExtra(Utils.EXTRA_DEVICE_ADDRESS, address)
				.putExtra(Utils.EXTRA_DEVICE_NAME, name)
				.setClass(this, DataActivity.class)
				.setAction(Utils.INTENT_ACK_CHOOSE_BT_DONE);
		startActivity(intent);
		finish();
	}

	@Override
	public void onClick(View v) {
		if (v == mBtnClose) {
			Intent mi = new Intent();
			mi.setClass(this, DataActivity.class);
			mi.setAction(Utils.INTENT_ACK_CHOOSE_BT_CANCEL);
			startActivity(mi);
			finish();
		}
		if (v == mBtnRestart) {
			mBtAdapter.startDiscovery();
//			if (mBtAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
//				//setBTDiscoverTime();
//			} else {
//				mBtAdapter.startDiscovery();
//			}
		}
		if (v == mBtnBind) {

		}
	}

}